package TestThreadLocal;

import lombok.Data;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author Mr.Wen
 * @Version 1.0
 */

public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        House house = new House();
        for (int i = 0; i < 5; i++) {
            int size = new Random().nextInt(5) + 1;
            new Thread(() -> {
                for (int j = 0; j < size; j++) {
                    house.sales();
                    house.salescount();
                }
                /*这里如果要显示ThreadLocal变量要在对应线程中去显示,如果在main线程中是显示不出来的*/
                System.out.println(Thread.currentThread().getName() + "号员工卖出:" + house.salecount.get() + "个房子");
            }).start();
        }
        TimeUnit.MILLISECONDS.sleep(200);
        System.out.println("总卖出: " + house.getCount());
    }
}

@Data
class House {
    private int count;
    ThreadLocal<Integer> salecount = new ThreadLocal<>().withInitial(() -> 0);

    public void salescount() {
        salecount.set(salecount.get() + 1);
    }

    public void sales() {
        ++count;
    }
}
